package com.hgzy.sys.controller;

import com.hgzy.sys.common.ActiveUser;
import com.hgzy.sys.common.ResultObj;
import com.hgzy.sys.domain.Loginfo;
import com.hgzy.sys.service.LoginfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 登陆控制器
 * @author : look-word
 * @date : 2022-01-14 20:18
 **/

@RestController
@RequestMapping("login")
public class LoginController extends BaseController{

    @Autowired
    private LoginfoService loginfoService;
    /**
     * 登陆验证
     * @param loginname 登陆名
     * @param pwd 密码
     * @return 统一返回的结果
     */
    @RequestMapping("login")
    public ResultObj login(String loginname, String pwd, HttpSession session, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginname, pwd);
        try {
            subject.login(token);
            ActiveUser  activeUser= (ActiveUser) subject.getPrincipal();
            session.setAttribute("user",activeUser);
            // 记录登陆日志
            Loginfo entity = new Loginfo();
            // 记录登陆人
            entity.setLoginname(bySessionGetUser(session).getName()+"-"+bySessionGetUser(session).getLoginname());
            // 记录登陆ip
            entity.setLoginip(request.getRemoteAddr());
            // 记录登陆时间
            entity.setLogintime(new Date());
            // 添加进数据库
            loginfoService.save(entity);
            return ResultObj.LOGIN_SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}
